//
//  PicListController.m
//  ExtModule
//
//  Created by CPX on 2018/9/11.
//  Copyright © 2018年 CPX. All rights reserved.
//

#import "PicListController.h"
#import "GreetCardApi.h"
#import "SingleImageCell.h"
#import "GreetCardModel.h"
#import "SDWebImageCodersManager.h"
#import "SDWebImageGIFCoder.h"
#import "PhotoBrowsePopupView.h"
#import "GreetTextListViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import <MobileCoreServices/MobileCoreServices.h>

/**
 贺卡列表页
 */
@interface PicListController ()
<
UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout
>
@property (nonatomic,strong)NSMutableArray  * dataSource;
@property (nonatomic,strong)UICollectionView * mycollectionview;
@end

@implementation PicListController
#pragma mark --- getter
- (NSMutableArray *)dataSource{
    if (!_dataSource){
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    [[SDWebImageCodersManager sharedInstance] addCoder:[SDWebImageGIFCoder sharedCoder]];

    
}

- (void)loadData{
    if(self.type == 0){
        [GreetCardApi getPictureListJsonArrayWithModelClass:[GreetPicModel class]
                                             NormalResponse:^(NSInteger status, id data, NSMutableArray *array) {
                                                 [self.dataSource addObjectsFromArray:array];
                                                 [self.mycollectionview reloadData];
        } exceptionResponse:^(NSError *error) {
            
        }];
    }
    else{
        [GreetCardApi getGifListJsonArrayWithModelClass:[GreetPicModel class]
                                         NormalResponse:^(NSInteger status, id data, NSMutableArray *array) {
                                             [self.dataSource addObjectsFromArray:array];
                                             [self.mycollectionview reloadData];

        } exceptionResponse:^(NSError *error) {
            
        }];
    }
}
- (void)initViews{
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
    layout.minimumInteritemSpacing = 5;
    layout.minimumLineSpacing = 5;
    float width  = (kScreenWidth  - 12 * 3) /  2;
    layout.itemSize = CGSizeMake(width, width * 0.75);
    
    self.mycollectionview = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) collectionViewLayout:layout];
    _mycollectionview.backgroundColor =[UIColor whiteColor];
    _mycollectionview.delegate = self;
    _mycollectionview.dataSource = self;
    _mycollectionview.showsHorizontalScrollIndicator = NO;
    _mycollectionview.showsVerticalScrollIndicator = NO;
    [_mycollectionview registerNib:[UINib nibWithNibName:NSStringFromClass(SingleImageCell.class) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass(SingleImageCell.class)];
    [self.view addSubview:self.mycollectionview];
    [self.mycollectionview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];

    
}
-(UICollectionViewCell * )collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    SingleImageCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass(SingleImageCell.class) forIndexPath:indexPath];
    GreetPicModel * model = self.dataSource[indexPath.row];
    cell.model = model;
    return  cell;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return  self.dataSource.count;
}
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(12, 12, 12, 12);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    GreetPicModel * model = self.dataSource[indexPath.row];
    if (self.type == 0){
        [self logEvent:@"gc_click_images_im" params:@{@"cardid":model.img_name}];
        GreetTextListViewController * txtListController = [[GreetTextListViewController alloc]init];
        txtListController.model = model;
        [self.navigationController pushViewController:txtListController animated:YES];
    }
    else{
        [self logEvent:@"gc_gif_set" params:@{@"gifid":model.img_name}];

        PhotoBrowsePopupView * photoView = [[PhotoBrowsePopupView alloc]init];

        photoView.url = model.img_gif;
        [photoView show];
        WeakSelf;
        photoView.onSaveToLocalEvent = ^(UIButton *button) {
            [weakSelf logEvent:@"gc_click_save"];
            [weakSelf requestPhotoAblumAuthorzation:model.img_gif];
            
        };
        photoView.onShareEvent = ^(UIButton *button) {
            [weakSelf logEvent:@"gc_click_share"];

            NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:model.img_gif]];
            
            
        
            
            UIActivityViewController * shareController  = [[UIActivityViewController alloc]initWithActivityItems:@[data] applicationActivities:nil];
            [self presentViewController:shareController animated:YES completion:nil];
            
            shareController.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
                if (completed) {
                    [weakSelf logEvent:@"gc_share_set" params:@{@"shareid":activityType}];
                    [weakSelf showHUDInWindow:@"Share Success"];

                    NSLog(@"completed");
                } else  {
                    NSLog(@"cancled");
                }
            };
            
        };
        
    }
}
#pragma mark--- 请求判断相册权限
-(void)requestPhotoAblumAuthorzation:(NSString *)img_gif{
    PHAuthorizationStatus oldStatus = [PHPhotoLibrary authorizationStatus];
    
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        //涉及到UI弹框 GCD到主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            switch (status) {
                case PHAuthorizationStatusAuthorized: {
                    //  保存图片到相册
                    [self saveGIFToAlbum:img_gif];
                        break;
                }
                    
                case PHAuthorizationStatusDenied: {
                    if (oldStatus == PHAuthorizationStatusNotDetermined) return;
                    
                    
                    break;
                }
                    
                case PHAuthorizationStatusRestricted: {
                    
                    break;
                }
                    
                default:
                    break;
            }
        });
    }];
}

-(void)saveGIFToAlbum:(NSString *)img_gif{

    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSData * data_image = [NSData dataWithContentsOfURL:[NSURL URLWithString:img_gif]];
        dispatch_async(dispatch_get_main_queue(), ^{
            WeakSelf;
            
            ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
            NSDictionary *metadata = @{@"UTI":(__bridge NSString *)kUTTypeGIF};
            [library writeImageDataToSavedPhotosAlbum:data_image metadata:metadata completionBlock:^(NSURL *assetURL, NSError *error) {
                [weakSelf showHUDInWindow:TLString(@"greeting_cards_download_successful")];
                if (error) {
                    NSLog(@"保存图片失败");
                }else{
                    NSLog(@"保存图片成功");
                }
            }] ;
        });
    });
  
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
